import React, { useImperativeHandle, useState } from 'react';
import { Modal, Upload, Button, Progress } from 'antd';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { uploadSeatSoundRecord } from 'seats/servers/servers';

/**
 * 批量上传props
 */
type IProps = {
  cRef: any;
  templateId: number; //录音模板id
};
// 存储回调函数
let ok = () => {};
/**
 * 批量上传state
 */
interface IState {
  // 当前操作弹出弹窗的可见性
  visible: boolean;
  // 是否上传中
  uploading: boolean;
}

/**
 * 批量上传管理操作
 */
export const MultipleUploadPop: React.FC<IProps> = ({ cRef, templateId }) => {
  const [visible, setVisible] = useState<boolean>(false); // 上传弹窗显示
  const [uploadFileList, setUploadFileList] = useState<any>([]); // 上传文件列表

  const [uploading, setUploading] = useState<boolean>(false); // 正在上传
  const [validate, setValidate] = useState<boolean>(true); // 上传录音：文件名、格式、大小验证是否通过
  const [progressVisible, setProgressVisible] = useState<boolean>(false); // 进度条弹窗
  const [progress, setProgress] = useState<number>(0); // 上传进度
  /**
   * 展开弹窗并设置类型
   */
  const open = (obj?: any, cb?: any) => {
    setVisible(true);
    setUploadFileList([]);
    setUploading(false);
    setValidate(true);
    setProgressVisible(false);
    setProgress(0);
    ok = cb;
  };
  useImperativeHandle(cRef, () => ({
    // 父组件数据和事件传递
    open: (obj: any, cb: any) => open(obj, cb),
  }));
  /**
   * 关闭弹窗
   */
  const close = () => {
    setVisible(false);
  };
  /**删除 */
  const handleRemove = (file: any) => {
    setValidate(true);
    const index = uploadFileList.indexOf(file);
    const newFileList = uploadFileList.slice();
    newFileList.splice(index, 1);
    setUploadFileList(newFileList);
    newFileList.map((item: any) => {
      if (item.status === 'error') {
        setValidate(false);
      }
      return null;
    });
  };

  /**
   * 上传前校验
   */
  const beforeUpload = (file: any, fileList: any): boolean => {
    // 存储批量文件
    setUploadFileList(fileList);
    console.log('上传前验证', file);
    const { name, type } = file;
    const nameArr = name.split('.');

    const isWav = (type && type.indexOf('wav') > -1) || nameArr[nameArr.length - 1] === 'wav';

    const isLt50M = file.size / 1024 / 1024 < 50;

    if (!isWav) {
      file.status = 'error';
      file.response = '请上传wav文件（只支持wav格式）!';
      setValidate(false);
      return false;
    }
    if (!isLt50M) {
      file.status = 'error';
      file.response = '文件大小超过50M!';
      setValidate(false);
      return false;
    }
    const soundRecordId = parseInt(nameArr[0]);
    if (!soundRecordId) {
      file.status = 'error';
      file.response = '文件名和话术ID格式不匹配!';
      setValidate(false);
      return false;
    }

    // 阻止-默认自动上传
    return false;
  };

  /**
   * 执行上传
   */
  const handleUpload = () => {
    // 验证不通过
    if (!validate) {
      return false;
    }
    // 验证通过
    console.log('执行上传');
    if (uploading) return false;
    setUploading(true);
    close();
    // 打开进度弹窗
    setProgressVisible(true);

    // 根据上传列表，批量请求上传接口
    const promiseList: Array<any> = [];

    uploadFileList.forEach((item: any) => {
      promiseList.push(doRequest(item));
    });
    // 计算-进度值
    const allWithProgress = (requests: Array<any>, callback: any) => {
      let index = 0;
      requests.forEach((item: any) => {
        item.then(() => {
          index++;
          const progress = (index * 100) / promiseList.length;
          callback(progress.toFixed(0));
        });
      });
      return Promise.all(requests);
    };
    allWithProgress(promiseList, (progress: number) => {
      console.log('1.进度条-百分比', progress);
      setProgress(progress);
    })
      .then(res => {
        console.log(res, '2.批量上传-结果');
        // 统计结果
        let success = 0; // 成功条数
        let fail = 0; // 失败条数
        res.map((fb: any) => {
          // fb为undefined，请求未发送
          if (!fb || fb[0] === 'error') {
            console.log('请求失败', fb[1].name);
            fail++;
          } else {
            console.log('请求成功', fb[1].name);
            success++;
          }
          return null;
        });
        setProgressVisible(false);
        ok();
        // 进度条关闭，出匹配结果
        Modal.info({
          title: '匹配结果通知',
          closable: true,
          content: (
            <div>
              {success}条录音上传成功，{fail}条录音上传失败
            </div>
          ),
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        setProgressVisible(false);
      });
  };
  /**接口请求 */
  const doRequest = (file: any) => {
    console.log(file, 'request');
    // 文件名称对应话术id，如果不是number类型，不执行上传
    const nameArr = file.name.split('.');
    const soundRecordId = parseInt(nameArr[0]);
    if (!soundRecordId) {
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    formData.append('templateId', JSON.stringify(templateId));

    return new Promise((resolve, reject) => {
      uploadSeatSoundRecord(soundRecordId, formData)
        .then(res => {
          resolve(['ok', file]);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
          console.log(error, 'error-request', file.name);
          resolve(['error', file]);
        });

      // 模拟mock接口请求
      // setTimeout(() => {
      //   var ok = Math.random() > 0.5; // 模拟请求成功或失败
      //   if (ok) {
      //     resolve(["ok", file]);
      //   } else {
      //     // reject(file.name + " fail"); // 如果调用reject就会使Promise.all()进行失败回调
      //     resolve(["error", file]); // Promise all的时候做判断  如果是error则说明这条请求失败
      //   }
      // }, 2000);
    });
  };

  return (
    <>
      <Modal
        title="批量上传"
        width={500}
        visible={visible}
        footer={
          <div className="upload-start">
            {!validate && (
              <div style={{ padding: '10px 0', color: 'red', float: 'left' }}>
                提示：包含不符合要求文件，请先移除再上传。
              </div>
            )}
            <Button
              type="primary"
              onClick={handleUpload}
              icon={uploading ? <LoadingOutlined /> : <UploadOutlined />}
              // 上传文件为空，或者上传文件验证不通过
              disabled={!uploadFileList.length || !validate}
            >
              开始批量上传
            </Button>
          </div>
        }
        destroyOnClose
        onCancel={() => {
          close();
        }}
      >
        <div className="upload-tips">
          批量上传步骤说明：
          <div>
            1.请先根据话术进行录音，以<span>wav格式</span>进行存储
          </div>
          <div>2.将每一条录音的文件名修改为对应"话术ID"</div>
          <div>3.最后点击"本地上传"，批量选择录音文件上传，等待文件上传完毕</div>
        </div>
        <Upload
          name="file"
          accept="audio/wav"
          // maxCount={50} // 需要升级antd
          fileList={uploadFileList}
          multiple={true}
          beforeUpload={(file: any, fileList: any) => beforeUpload(file, fileList)}
          onChange={info => {
            console.log(info, 'onchange后');
          }}
          onRemove={(file: any) => handleRemove(file)}
          progress={{
            strokeColor: {
              '0%': '#108ee9',
              '100%': '#87d068',
            },
            strokeWidth: 3,
            format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`,
          }}
        >
          {uploadFileList.length <= 0 && (
            <Button style={{ marginRight: 20 }} type="primary">
              选择文件
            </Button>
          )}
        </Upload>
      </Modal>
      <Modal
        style={{
          paddingBottom: 30,
        }}
        title="批量上传"
        visible={progressVisible}
        footer={null}
        onCancel={() => {
          setProgressVisible(false);
        }}
      >
        <div style={{ textAlign: 'center' }}>正在上传...</div>
        <Progress percent={progress} />
      </Modal>
    </>
  );
};
